package cn.kattomy.shop.prevcategory.adminaction;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.kattomy.shop.prevcategory.service.PrevCategoryService;
import cn.kattomy.shop.prevcategory.vo.PrevCategory;

public class AdminPrevCategory extends ActionSupport implements ModelDriven<PrevCategory> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//模型驱动使用的对象
	private PrevCategory prevCategory = new PrevCategory(); 
	@Override
	public PrevCategory getModel() {
		return prevCategory;
	}
	
	//注入前置分类Service
	private PrevCategoryService prevCategoryService;
	public void setPrevCategoryService(PrevCategoryService prevCategoryService) {
		this.prevCategoryService = prevCategoryService;
	}
	
	//文件上传需要的参数
	private File upload;//上传的文件
	private String uploadFileName;//接收文件上传的文件名
	private String uploadContextType;//接收文件上传的文件的 MIME的类型
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public void setUploadContextType(String uploadContextType) {
		this.uploadContextType = uploadContextType;
	}
	
	public String findAll(){
		List<PrevCategory> prevList = prevCategoryService.findAll();
		ActionContext.getContext().getValueStack().set("prevList", prevList);
		return "findAll";
	}
	
	public String edit(){
		prevCategory = prevCategoryService.findByPcid(prevCategory.getPcid());
		return "edit";
	}
	
	public String delete(){
		prevCategory = prevCategoryService.findByPcid(prevCategory.getPcid());
		prevCategoryService.delete(prevCategory);
		return "delete";
	}
	
	public String update(){
		prevCategoryService.update(prevCategory);
		return "update";
	}
	
	public String save() throws IOException{
		//调用 Service 完成保存操作
		if (upload != null) {
			//获得文件上传的磁盘绝对路径
			String realPath = ServletActionContext.getServletContext()
					.getRealPath("/images");
			//创建一个文件
			File diskFile = new File(realPath + "//" + uploadFileName);
			//文件上传
			FileUtils.copyFile(upload, diskFile);
			prevCategory.setImage("images/" + uploadFileName);
		}
		prevCategoryService.save(prevCategory);
		
		return "save";
	}
}
